const router = require("koa-router")();
const Joi = require("joi");
const { Payment, Notification } = require("easy-alipay");
const defaultConfig = require("easy-alipay/lib/default-config");
const alipaySubmit = require("easy-alipay/lib/alipay-submit");

/**
 *
 * @api {get} /home/app/pay/alipay 支付宝支付
 * @apiDescription 支付宝支付
 * @apiGroup Pay
 * @apiVersion 0.0.1
 *
 * @apiParam {Number} id 账单ID
 *
 * @apiSampleRequest /home/app/pay/alipay
 *
 */

router.get("/alipay", async (ctx, next) => {
  const { id, redirect } = ctx.query;
  const valid = await ctx.validate({ id: id }, { id: Joi.number().required() });
  if (!valid) {
    ctx.error("参数有误");
    return;
  }
  const notifyUrl = "http://" + ctx.host + "/pay/notify";
  const showUrl = "http://" + ctx.host;
  const returnUrl =
    "http://" + ctx.host + `/pay/return?id=${id}&redirect=${redirect}`;
  const trade = await BaaS.Models.trade
    .query(qb => {
      qb.where("id", "=", id);
      qb.where("status", "=", 0);
    })
    .fetch();
  if (!trade) {
    ctx.error("账单不存在或者已支付");
    return;
  }
  const { partner, key, account } = ctx.config("alipay");
  const url = await Payment.createDirectPay(
    partner,
    key,
    account,
    "青否云",
    trade.tradeid,
    trade.money,
    "青否云",
    showUrl,
    notifyUrl,
    returnUrl
  );
  ctx.redirect(url);
});
router.get("/return", async (ctx, next) => {
  const { id, redirect } = ctx.query;
  // 订单信息，修改订单状态
  const tradeInfo = await BaaS.Models.trade
    .query({ where: { id: id } })
    .fetch();
  await BaaS.Models.trade.forge({ id: id, status: 1 }).save();
  // 查询log数据
  const constLog = await BaaS.Models.cost_log
    .query({
      where: { orderid: tradeInfo.tradeid }
    })
    .fetch();
  // 修改log状态
  await BaaS.Models.cost_log.forge({ id: constLog.id, status: 1 }).save();
  // 查询用户信息，更新用户余额
  const userInfo = await BaaS.Models.user
    .query({ where: { id: tradeInfo.id } })
    .fetch();
  await BaaS.Models.user
    .forge({ id: tradeInfo.id, money: userInfo.money + tradeInfo.money })
    .save();
  ctx.redirect(redirect || "http://dev.qingful.com/home/dashboard/money");
});
router.post("/notify", async (ctx, next) => {
  const notifyData = ctx.post;
  const { partner, key, account } = ctx.config("alipay");
  try {
    const data = await Notification.directPayNotify(notifyData, partner, key);
    if (data.tradeStatus == "TRADE_SUCCESS") {
      ctx.payTrue.bind(ctx)(data.outTradeNo);
      ctx.view("success");
    } else {
      ctx.view("fail");
    }
  } catch (err) {
    console.error(err);
  }
});

module.exports = router;
